package com.example.seckill.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.seckill.service.RateLimiterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class RateLimiterController {

    @Autowired
    private RateLimiterService rateLimiterService;

    int count = 0;


    @GetMapping("/getToken")
    public String rateLimiter() {

        if (rateLimiterService.tryAcquireSeckill()) {
            count++;
            log.info("获取到令牌，进行秒杀 {}", count);
            return "获取令牌成功";
        } else {
            return "获取令牌失败";
        }
    }


    @SentinelResource(value = "sentinelLimiter", blockHandler = "exceptionHandler")
    @GetMapping("/sentinelLimiter")
    public String sentinelLimter() {

        count++;
        log.info("限流{}", count);
        return "success";
    }

    public String
    exceptionHandler
            (
                    String id, BlockException e
            ) {
        e
                .
                        printStackTrace
                                ();

        return

                "错误发生在"

                        +
                        id
                ;
    }
}
